using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;

namespace IpMacConfiguratorFramework
{
    public static class NetworkHelper
    {
        public class NetworkAdapterInfo
        {
            public string Name { get; set; }
            public string Id { get; set; }
            public string MacAddress { get; set; }
            public string IpAddress { get; set; }
            public string Description { get; set; }
            public string SubnetMask { get; set; }
            public string Gateway { get; set; }
            public string DnsAddresses { get; set; }
        }

        // 获取所有有线网卡（过滤WIFI/VPN/虚拟网卡），并获取当前IP属性
        public static List<NetworkAdapterInfo> GetWiredAdapters()
        {
            var adapters = new List<NetworkAdapterInfo>();
            foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                // 检查网卡类型
                if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                    nic.NetworkInterfaceType.ToString().Contains("Gigabit"))
                {
                    // 检查网卡描述，过滤掉不需要的网卡类型
                    string description = nic.Description.ToLower();
                    if (!description.Contains("virtual") &&
                        !description.Contains("wifi") &&
                        !description.Contains("vpn") &&
                        !description.Contains("bluetooth") &&  // 过滤蓝牙适配器
                        !description.Contains("wireless") &&   // 过滤无线网卡
                        !description.Contains("mobile") &&     // 过滤移动网络适配器
                        !description.Contains("tunnel"))       // 过滤隧道适配器
                    {
                        var ipProps = nic.GetIPProperties();
                        var ipv4Address = ipProps.UnicastAddresses
                            .FirstOrDefault(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

                        string ip = ipv4Address != null ? ipv4Address.Address.ToString() : string.Empty;
                        string subnet = ipv4Address != null ? ipv4Address.IPv4Mask.ToString() : string.Empty;
                        string gateway = ipProps.GatewayAddresses.Count > 0 ? ipProps.GatewayAddresses[0].Address.ToString() : string.Empty;
                        string dns = string.Join(",", ipProps.DnsAddresses.Where(d => d.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).Select(d => d.ToString()));

                        adapters.Add(new NetworkAdapterInfo
                        {
                            Name = nic.Name,
                            Id = nic.Id,
                            MacAddress = FormatMac(nic.GetPhysicalAddress().ToString()),
                            IpAddress = ip,
                            Description = nic.Description,
                            SubnetMask = subnet,
                            Gateway = gateway,
                            DnsAddresses = dns
                        });
                    }
                }
            }
            return adapters;
        }

        // 将MAC地址格式化为 XX-XX-XX-XX-XX-XX 的形式
        public static string FormatMac(string mac)
        {
            if (string.IsNullOrEmpty(mac)) return string.Empty;
            mac = mac.Replace(":", "").Replace("-", "").ToUpper();
            if (mac.Length != 12) return mac; // 如果不是12位十六进制，不进行格式化

            return string.Join("-", Enumerable.Range(0, 6).Select(i => mac.Substring(i * 2, 2)));
        }

        // 获取指定网卡的IPv4地址 (不再单独使用此方法，已合并到GetWiredAdapters)
        // private static string GetIpAddress(NetworkInterface nic)
        // {
        //     var ipProps = nic.GetIPProperties();
        //     var addr = ipProps.UnicastAddresses
        //         .FirstOrDefault(a => a.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
        //     return addr != null ? addr.Address.ToString() : string.Empty;
        // }

        // 检测网关连接状态
        public static bool CheckGatewayConnection(string gateway, out string message)
        {
            try
            {
                if (string.IsNullOrEmpty(gateway))
                {
                    message = "网关地址为空，无法检测连接状态";
                    return false;
                }

                using (var ping = new Ping())
                {
                    int successCount = 0;
                    long totalTime = 0;
                    List<long> times = new List<long>();

                    // 发送4个ping包
                    for (int i = 0; i < 4; i++)
                    {
                        var reply = ping.Send(gateway, 2000); // 设置2秒超时
                        if (reply.Status == IPStatus.Success)
                        {
                            successCount++;
                            totalTime += reply.RoundtripTime;
                            times.Add(reply.RoundtripTime);
                        }
                    }

                    // 计算统计信息
                    if (successCount > 0)
                    {
                        double avgTime = (double)totalTime / successCount;
                        double minTime = times.Min();
                        double maxTime = times.Max();
                        double lossRate = (4 - successCount) * 25; // 计算丢包率

                        message = $"网关 {gateway} 连接测试结果：\r\n" +
                                $"发送: 4 个数据包\r\n" +
                                $"接收: {successCount} 个数据包\r\n" +
                                $"丢失: {4 - successCount} 个数据包 ({lossRate}% 丢失)\r\n" +
                                $"往返时间统计(ms):\r\n" +
                                $"    最短 = {minTime}ms\r\n" +
                                $"    最长 = {maxTime}ms\r\n" +
                                $"    平均 = {avgTime:F2}ms";
                        return successCount >= 2; // 如果成功接收2个或以上包，认为连接正常
                    }
                    else
                    {
                        message = $"网关 {gateway} 连接失败，所有数据包均未收到响应";
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                message = $"检测网关连接时发生错误: {ex.Message}";
                return false;
            }
        }
    }
} 